#include "curl_post_to_bottle.hpp"
#include <iostream>

static const std::string g_str_post_url("http://127.0.0.1:8020/post_test");

CCurlPostToBottle::CCurlPostToBottle() 
{
        p_curl_ = NULL;
        p_slist_ = NULL;
}

CCurlPostToBottle::~CCurlPostToBottle() 
{
        if (p_slist_) {
                curl_slist_free_all(p_slist_);
        }
        if (p_curl_) {
                curl_easy_cleanup(p_curl_);
        }
        curl_global_cleanup();
}

bool CCurlPostToBottle::init()
{
        res_ = curl_global_init(CURL_GLOBAL_ALL);
        if (res_ != CURLE_OK) {
                std::cerr << "curl_global_init failed, error msg: "
                        << curl_easy_strerror(res_) << std::endl;
                return false;
        }
        p_curl_ = curl_easy_init();
        if (!p_curl_) {
                std::cerr << "curl_easy_init failed." << std::endl;
                return false;
        }
        res_ = curl_easy_setopt(p_curl_, CURLOPT_URL, g_str_post_url.c_str());
        if (res_ != CURLE_OK) {
                std::cerr << "curl_easy_setopt failed, error msg: "
                        << curl_easy_strerror(res_) << std::endl;
                return false;
        }
        p_slist_ = curl_slist_append(p_slist_, "Content-type: application/json");
        if (!p_slist_) {
                std::cerr << "curl_slist_append failed." << std::endl; 
                return false;
        }
        res_ = curl_easy_setopt(p_curl_, CURLOPT_HTTPHEADER, p_slist_);
        if (res_ != CURLE_OK) {
                std::cerr << "curl_easy_setopt failed, error msg: "
                        << curl_easy_strerror(res_) << std::endl;
                return false;
        }
        return true;
}

bool CCurlPostToBottle::post(std::string &str_post_data)
{
        res_ = curl_easy_setopt(p_curl_, CURLOPT_COPYPOSTFIELDS, 
                str_post_data.c_str());
        if (res_ != CURLE_OK) {
                std::cerr << "post, curl_easy_setopt failed, error msg: "
                        << curl_easy_strerror(res_) << std::endl;
                return false;
        }
        res_ = curl_easy_perform(p_curl_);
        if (res_ != CURLE_OK) {
                std::cerr << "curl_easy_perform failed, error msg: "
                        << curl_easy_strerror(res_) << std::endl;
                return false;
        }
        return true;
}